<?php
/*
 * 购物车
 */
namespace Mobile\Controller;
use Mobile\Model\goodsModel;
use Mobile\Model\deliveryModel;
use Mobile\Model\cartModel;
use Mobile\Model\areaModel;
use Mobile\Model\goodsguigeModel;

class CartController extends BaseController {
    
    public $goodsModel;
    public $cartModel;
    public $goodsguigeModel;
    public $grade_info;
    public $areaModel;
    
    public function __construct() {
        parent::__construct();
        $this->goodsModel = new goodsModel();
        $this->cartModel = new cartModel();
        $this->goodsguigeModel = new goodsguigeModel();
        $this->areaModel = new areaModel();
        $goodslist = $this->goodsModel->select();
        $this->assign('goodslist',$goodslist);
        
    }
    
    
    
    /*
     * 获取收货地址信息
     */
    protected function _get_delivery_data(){
        $allow = array(
            "delivery_name","address","delivery_mobile","province","city","county","wechat_user"
        );
        $must = array(
            "delivery_name","address","delivery_mobile","province","city","county"
        );
        $data = param_filter($_POST,$allow,$must,true,true);
        if(empty($data)){
            return false;
        }
        return $data;
    }
    
    /*
     * 收货地址
     */
    public function address(){
    
        $deliveryModel = new deliveryModel();
    
        if(IS_AJAX){
            //添加收货地址到数据库
            $delivery_data = $this->_get_delivery_data();
            if(empty($delivery_data)){
                return_json(1,"请检查地址信息");
            }
    
            $delivery_data['uid'] = $this->uid;
             
            //插入数据库
            $dres = $deliveryModel->addDelivery($delivery_data);
            if($dres){
                return_json(0,"已更新");
            }
            return_json(1,"编辑失败");
        }
    
        $seo_data = array(
            "title" => $this->lang['cart_address'],
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
    
        //取出我的默认收货地址
    
        $delivery = $deliveryModel->getDeliveryList(array('uid'=>$this->uid));
        if(!empty($delivery)){
            $this->assign('delivery',$delivery[0]);//第一条
        }
        
        $share_data = array(
            "title" => $this->lang['cart_address'],
        );
        $this->setShare($share_data);
    
        $this->display();
    }
    
    /*
     * 从购物车中删除
     */
    public function del(){
        $id = post('id');
    
        if(empty($id)){
            return_json(1,"商品参数错误");
        }
    
        $where = array(
            "goods_id" => array("IN",$id),
            "uid" => $this->uid
        );
    
        $res = $this->cartModel->where($where)->delete();
        if($res){
            return_json(0,"已删除","","/mobile/cart/mycart");
        }
        return_json(1,"删除失败");
    }
    
    
    /*
     * 把商品放入购物车
     */
    public function addgoods(){
        
        $goods_id = get("goods_id");
        
        $nums = 1;//商品数量
        
        $guige_id = get('gg_id');//规格id
        $guige_id = intval($guige_id);
     
        
        if(!$goods_id){
            return_json(1,"商品参数错误");
        }
        
        if(!IS_AJAX){
            return_json(1,"提交方式有误");
        }
        
        //查找是否有该商品
        $where = array(
            "goods_id" => $goods_id,
            "uid" => $this->uid
        );
        

        //查看当前商品是否可以加入购车
        //查看库存
        $where_g = array(
            "goods_id" => $goods_id,
        );
        $goodsinfo = $this->goodsModel->getGoods($where_g);
        
        
        if($_GET['guige_new']){
            //jinjianghai test
            $guige= unserialize($goodsinfo['guige_new']);
            $guigeString = $_GET['guige_new'];
            $guigeArr = explode("-",$guigeString);
            foreach($guigeArr as $g){
                $arr = explode("_",$g);
                 
                $guige_new[] .= $guige[$arr[0]][$arr[1]];
            }
            
            $guige_new['name'] = implode("-",$guige_new);
            $guige_new['id'] = $guigeString;
           
            $where['guige_id_new'] = $guige_new['id'];
           
        }
        
       
        if($goodsinfo['ischeck'] !=1){
            return_json(1,"当前商品已下架");
        }
        
        //判断商品要成倍购买或起订量
        
        //成倍购买和最小购买之间的关系
        if($goodsinfo['double_buy']>1){
            $goodsinfo['min_buy'] = ($goodsinfo['double_buy'] > $goodsinfo['min_buy']) ? $goodsinfo['double_buy'] : $goodsinfo['min_buy'];//最小购买数
        }
        
        //最小购买和商品数量之间的关系
        if($goodsinfo['min_buy']>0){
            $nums = ($nums > $goodsinfo['min_buy']) ? $nums : $goodsinfo['min_buy'];//最小购买数
        }
        
        //成倍购买和商品数量之间的关系
        if($goodsinfo['double_buy']>1){
            //需要成倍购买
            $quyu = $nums%$goodsinfo['double_buy'];
            if($quyu>0){
                $nums -= $quyu;
            }
        }
        
        if($goodsinfo['stock']<$nums){
            return_json(1,"当前商品库存不足");
        }
        
        $res = $this->cartModel->getCart($where);
    
        if($res){
            //已经存在该商品,数量加+
            if($goodsinfo['double_buy']>1) {
                return_json(0,"已添加");
            }else{
                $r = $this->cartModel->where($where)->setInc('goods_num',$nums);
            }
        }else{
            //不存在,添加商品到购物车

            //等级价格
            $grade_id = $this->memberinfo['grade_id'];
            $grade_id = $grade_id ? $grade_id : 0;
            
//            if($grade_id == 3){
//                $goodsinfo['shop_price'] = $goodsinfo['ceo_price'];
//            }else if($grade_id > 3){
//                $goodsinfo['shop_price'] = $goodsinfo['king_price'];
//            }
            $goods['shop_price'] = $goods['grade'.$grade_id.'_price'];
            $data = array(
                "goods_id" => $goods_id,
                "goods_name" => $goodsinfo['goods_name'],
                "shop_price" => $goodsinfo['shop_price'],
                "uid" => $this->uid,
                "goods_num" => $nums,
                "create_time" => date("Y-m-d H:i:s"),
                "guige_id" => $guige_id,
                "guige_name" => $guige_new['name'],
                "guige_id_new" => $guige_new['id']
            );
            
            $r = $this->cartModel->addCart($data);
        }
                
        if($r){
            return_json(0,"已添加");
        }
            
        return_json(1,"添加失败,请重试");
        
    }
    
    /*
     * 直接购物
     */
    public function index(){
        
        //我的等级id
        $grade_id = $this->memberinfo['grade_id'];
        
        if($grade_id<=2){
            //$this->error2("CEO会员请联系皇冠下单","/mobile");exit;
        }
        
        $seo_data = array(
            "title" => $this->lang['cart_index'],
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        
        //获取商品信息
        $goods_id = get('goods_id');

        if($goods_id==2 || $goods_id==3) {
            $this->error2("商品参数错误");exit;
        }

        $guige_id = get('gg_id');//规格id
        $guige_id = intval($guige_id);
        
        if(empty($goods_id)){
            $this->error2("商品参数错误","/mobile/goods/index");exit;
        }
        
        $where  = "goods_id = ".$goods_id." AND ischeck=1 AND stock>0";
        $goods = $this->goodsModel->getGoods($where);

        if(empty($goods)){
            $this->error2("该商品已下架","/mobile/goods/index");exit;
        }
        
        //取出我的默认收货地址
        $deliveryModel = new deliveryModel();
        $delivery = $deliveryModel->getDeliveryList(array('uid'=>$this->uid));
        if(!empty($delivery)){
            $this->assign('delivery',$delivery[0]);//第一条
        }
        
        //商品折扣
        $goods['discount'] = 1;//无折扣
        
        $goods['num'] = $nums = 1;
        //判断商品要成倍购买或起订量
        
        //成倍购买和最小购买之间的关系
        if($goods['double_buy']>1){
            $goods['min_buy'] = ($goods['double_buy'] > $goods['min_buy']) ? $goods['double_buy'] : $goods['min_buy'];//最小购买数
        }
        
        //最小购买和商品数量之间的关系
        if($goods['min_buy']>0){
            $nums = ($nums > $goods['min_buy']) ? $nums : $goods['min_buy'];//最小购买数
        }
        
        //成倍购买和商品数量之间的关系
        if($goods['double_buy']>1){
            //需要成倍购买
            $quyu = $nums%$goods['double_buy'];
            if($quyu>0){
                $nums -= $quyu;
            }
        }
        $goods['num'] = $nums;
        
        
        if($_GET['guige_new']){
        //jinjianghai  test
        $guige= unserialize($goods['guige_new']);
        $guigeString = $_GET['guige_new'];
        $guigeArr = explode("-",$guigeString);
        foreach($guigeArr as $g){
            $arr = explode("_",$g);
            	
            $guige_new[] .= $guige[$arr[0]][$arr[1]];
        }
        
        $goods['guige_name_new'] = implode("-",$guige_new);
        $goods['guige_id_new'] = $guigeString;
       
        }
        
        if($goods['score_rate']<=0){
            $no_score = true;
            $this->assign('no_score',true);
        }
        
        $this->memberinfo['score']=0;
            $this->assign('memberinfo',$this->memberinfo);
        
        //判断商品类型，是否包含非品牌商品
        $is_brand = ($goods['is_brand'] == 1) ? true : false;
        $this->assign('is_brand',$is_brand);
        
        //等级价格
        $grade_id = $this->memberinfo['grade_id'];
        $grade_id = $grade_id ? $grade_id : 0;
//        if($grade_id == 3){
//            $goods['shop_price'] = $goods['ceo_price'];
//        }else if($grade_id > 3){
//            $goods['shop_price'] = $goods['king_price'];
//        }
        $goods['shop_price'] = $goods['grade'.$grade_id.'_price'];

        if($goods['freight_payer']==1) {
            $goods['goods_weight'] = 0;
        }
        $goods_info[] = $goods;
        
        $this->assign('goods_money',$goods['shop_price']);

        $this->assign("goods_info",$goods_info);
        
        $this->assign('is_shiwu',$goods['is_shiwu']);//实物或虚拟
        $this->assign("grade",$this->memberinfo['grade_id']);

        $share_data = array(
            "title" => $this->lang['cart_index'],
            "img" => $this->memberinfo['headimgurl'],
            "params" => "goods_id=".$goods_id,
        );
        $this->setShare($share_data);
        
        $this->display();
    }
    
    /*
     * 加购物车下单
     */
    public function mycart(){
        
        //我的等级id
        $grade_id = $this->memberinfo['grade_id'];
        
        if($grade_id<=2){
            //$this->error2("CEO会员请联系皇冠下单","/mobile");exit;
        }
        
        $seo_data = array(
            "title" => $this->lang['cart_mycart'],
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        
        //查找购物车商品
        $where = array(
            "uid" => $this->uid
        );
        
        
        $cartlist = $this->cartModel->getCartLists($where);
        
        
        if(empty($cartlist)){
            
            $this->display("empty");
        }else{

            $goods_info = array();
            $is_shiwu = 0;//是否实物
            
            $yunfei = 0;
            //获取商品信息
            //过滤掉无效的商品
            $goods_money = 0;
            
            //等级价格
            $grade_id = $this->memberinfo['grade_id'];
            $grade_id = $grade_id ? $grade_id : 0;
            
            foreach($cartlist as $k=>$v){
                
                //获取商品信息
                $where = array(
                    "ischeck" =>1,
                    "goods_id" => $v['goods_id']
                );
                $goods = $this->goodsModel->getGoods($where);
                if(!$goods) {
                    continue;
                }
//                if($grade_id == 3){
//                    $goods['shop_price'] = $goods['ceo_price'];
//                }else if($grade_id > 3){
//                    $goods['shop_price'] = $goods['king_price'];
//                }
                $goods['shop_price'] = $goods['grade'.$grade_id.'_price'];

                if($goods['freight_payer']==1) {
                    $goods['goods_weight'] = 0;
                }

                if($goods){
                    if($goods['stock']<$v['goods_num']){
                        $goods['num'] = $goods['stock'];
                    }else{
                        $goods['num'] = $v['goods_num'];
                    }
                    
                    $nums = $v['goods_num'];
                    if($goods['double_buy']>1){
                        $goods['min_buy'] = ($goods['double_buy'] > $goods['min_buy']) ? $goods['double_buy'] : $goods['min_buy'];//最小购买数
                    }

                    //最小购买和商品数量之间的关系
                    if($goods['min_buy']>0){
                        $nums = ($nums > $goods['min_buy']) ? $nums : $goods['min_buy'];//最小购买数
                    }

                    //成倍购买和商品数量之间的关系
                    if($goods['double_buy']>1){
                        //需要成倍购买
                        $quyu = $nums%$goods['double_buy'];
                        if($quyu>0){
                            $nums -= $quyu;
                        }
                    }
                    $goods['num'] = $nums;
                    if($goods['num']>=$goods['min_buy']) {
                        $goods['min_buy'] = 0;
                    }
                    $goods['guige_id'] = $v['guige_id'];
                    $goods['guige_name_new'] = $v['guige_name'];
                    $goods['guige_id_new'] = $v['goods_id'];
                    $goods_money += $goods['num']*$goods['shop_price']; 
                    
                    if ($goods['is_shiwu'] == 1){
                        $is_shiwu = 1;
                    }
                    
                    $goods['discount'] = 1;//无折扣
                    $goods_info[] = $goods;
                }else{
                    continue;
                }
            }

            //没有可以购买的商品
            if(empty($goods_info)){
                $this->display("empty");exit;
            }
            
            $is_brand = true; 
            foreach($goods_info as $k=>$v){

                //是否包含重消商品
                if($v['is_brand'] == 0){
                    $is_brand = false;
                }
                
            }
            $this->assign('is_brand',$is_brand);
            $this->assign("grade",$this->memberinfo['grade_id']);
            $this->assign('goods_money',$goods_money);
            
            //取出我的默认收货地址
            $deliveryModel = new deliveryModel();
            $delivery = $deliveryModel->getDeliveryList(array('uid'=>$this->uid));
            if(!empty($delivery)){
                $this->assign('delivery',$delivery[0]);//第一条
            }
            
            $this->assign("yunfei",$yunfei);

            $this->assign("goods_info",$goods_info);

            $this->assign('is_shiwu',$is_shiwu);//实物或虚拟
            
            $share_data = array(
                "title" => $this->lang['cart_mycart'],
            );
            $this->setShare($share_data);
            
            $this->memberinfo['score']=0;
            $this->assign('memberinfo',$this->memberinfo);
            
            $this->display('index');
        }
        
        
    }
    
    public function getuserinfo () {
        $uid = get('uid');
        if(!$uid) {
            return_json(1,'请填写下单人ID');
        }
        $len = strlen($uid);
        if($len==11) {
            $user = $this->memberModel->where(array('mobile'=>$uid))->find();
        }else {
            $user = $this->memberModel->where(array('uid'=>$uid))->find();
        }
        if(empty($user)) {
            return_json(1,'下单人不存在');
        }
        if($user['uid']==$this->uid) {
            return_json(1,'下单人为当前用户');
        }
        if($user['grade_id']!=2) {
            return_json(1,'只能替合伙人等级用户下单');
        }
        return_json(0,'success',$user);
    }
    
    public function baodan () {
        $gradearr = M('grade')->getField('grade_id,grade_name',true);
        $this->assign('gradearr',$gradearr);
        $seo = array(
            'title' => '升级'
        );
        $this->setSeo($seo);
        $this->display();
    }
    
    
    public function tihuo () {
        $seo = array(
            'title' => '提货'
        );
        $this->setSeo($seo);
        $this->display();
    }
    
    public function buhuo () {
        $seo = array(
            'title' => '补货'
        );
        $this->setSeo($seo);
        $this->display();
    }
    
    public function transfer () {
        $seo = array(
            'title' => '拨货'
        );
        $this->setSeo($seo);
        $this->display();
    }
    
    
    
    //下单人, 复购
    public function getuserinfo2() {
        $uid = get('uid');
        if(!$uid) {
            return_json(1,'请填写收货人ID');
        }

        $user = $this->memberModel->where(array('uid'=>$uid))->field("uid,nickname,realname,grade_id,headimgurl,refer_uid")->find();
    
        if(empty($user)) {
            return_json(1,'收货人不存在');
        }

        $user['realname'] = $user['realname']?$user['realname']:$user['nickname'];
    
        return_json(0,'success',$user);
    }
    
    public function daili () {
        $grade = get('grade',3);
        
        $seo = array(
            'title' => $grade==3?'升级店长':'升级资深店长'
        );
        $this->setSeo($seo);
        $this->display();
    }

    public function jiameng () {
        $seo = array(
            'title' => '申请代理'
        );
        $this->setSeo($seo);
        $min = $this->memberinfo['grade_id']>=5?($this->memberinfo['grade_id']+1):5;
        $where = array(
            'grade_id' => array('between',array($min,6))
        );
        $gradeArr = M('grade')->where($where)->select();
        $this->assign('gradeArr',$gradeArr);
        $this->display();
    }
    
    public function getProvinceList () {
        $where = array(
            'level' => 1
        );
        $list = $this->areaModel->where($where)->select();
        foreach($list as $k=>$v) {
            $list[$k]['children'] = array();
        }
        return_json(0,'success',$list);
    }
    
    public function getProvinceChildren () {
        $area_id = get('area_id');
        $new = array();
        $new[] = $this->areaModel->where(array('area_id'=>$area_id))->find();
        $where = array(
            'parentid' => $area_id,
            'level' => 2
        );
        $list = $this->areaModel->where($where)->select();

        foreach($list as $v) {
            if($v['is_zhixia']==0) {
                $new[] = $v;
            }
            $where = array(
                'parentid' => $v['area_id'],
                'level' => 3
            );
            $countys = $this->areaModel->where($where)->select();
            foreach($countys as $vv) {
                $vv['area_name'] = $v['area_name'].'-'.$vv['area_name'];
                $new[] = $vv;
            }
        }

        foreach($new as $k=>$v) {
            $new[$k]['money_text'] = round($v['money']/10000,2).'万';
        }

        return_json(0,'success',$new);
    }

    public function search () {
        $key = get('key');
        if(!$key){
            return_json(0,'',array());
        }
        $where = array(
            'area_name' => array('like','%'.$key.'%'),
            'is_zhixia' => 0
        );
        $list = $this->areaModel->where($where)->select();
        foreach($list as $k=>$v) {
            $list[$k]['money_text'] = round($v['money']/10000,2).'万';
            if($v['level']==3) {
                $city = $this->areaModel->where(array(
                    'area_id' => $v['parentid']
                ))->find();
                $list[$k]['area_name'] = $city['area_name'].'-'.$list[$k]['area_name'];
            }elseif($v['level']==2){
                $city = $v;
            }
            if($city) {
                $province = $this->areaModel->where(array(
                    'area_id' => $city['parentid']
                ))->find();
                $list[$k]['area_name'] = $province['area_name'].'-'.$list[$k]['area_name'];
            }
        }
        return_json(0,'',$list);
    }

    /* 申请代理 */
    public function apply () {
        if(IS_AJAX) {
            $applyModel = M('apply');
            $uid = $this->uid;
            $data = $_POST;
            if(!$data['grade_id']) {
                return_json(1,'请选择等级');
            }
            if($this->memberinfo['grade_id']>=$data['grade_id']) {
                return_json(1,'无法申请低等级代理');
            }
            if($data['grade_id']<5 || $data['grade_id']>6) {
                return_json(1,'error');
            }
            if(!$data['province']||!$data['city']||!$data['county']) {
                return_json(1,'请选择地区');
            }
            //自己有等待中申请
            $where = array(
                'uid' => $this->uid,
                'status' => 0
            );
            $old = $applyModel->where($where)->find();
            if($old) {
                return_json(1,'您的申请还在审核中，请耐心等待');
            }
            $apply = array(
                'uid' => $this->uid,
                'area_id' => $area_id,
                'money' => 29800,
                'type' => 2,
                'create_time' => date('Y-m-d H:i:s'),
                'grade_id' => $data['grade_id'],
                'delivery' => json_encode(array(
                    'province' => $data['province'],
                    'city' => $data['city'],
                    'county' => $data['county']
                ))
            );
            $applyModel->add($apply);

            return_json(0,'已提交申请，请等待审核');
        }
    }


    public function getAddressList() {
        $addressModel = M('address');
        $list = $addressModel->where(array('uid'=>$this->uid))->field('*,mobile as tel,address as detail,concat(province,city,county,address) as address')->order('is_default DESC,id DESC')->select();
        if($list){
            return_json(0,'success',$list);
        }
        return_json(1,'无收货地址');
    }
    public function addAddress() {
        $addressModel = M('address');
        $allow = array('id','name','mobile','province','city','county','address','is_default','country');
        $data = param_filter($_POST, $allow);
        if(!check_mobile($data['mobile'])) {
            return_json(1,'手机号格式错误');
        }
        if(!$data['name']) {
            return_json(1,'请填写姓名');
        }
        if(!$data['province'] || !$data['city'] || !$data['county'] || !$data['address']) {
            return_json(1,'请填写完整');
        }
       
        $areaModel = M('area');
        $area = $areaModel->where(array('shortname'=>$data['province'],'level'=>1))->find();
        $data['province_id'] = $area['area_id'];
        
        if($data['is_default']==1) {
            $addressModel->where(array('uid'=>$this->uid))->setField('is_default',0);
        }
        
        if($data['id']){
            $addressModel->where(array('id'=>$data['id'],'uid'=>$this->uid))->save($data);
            $address = $addressModel->where(array('id'=>$data['id']))->find();
            return_json(0,'修改成功',$address);
        }
        $data['uid'] = $this->uid;
        $old = $addressModel->where(array('uid'=>$this->uid,'is_default'=>1))->find();
        if(!$old){
            $data['is_default'] = 1;
        }
        $res = $addressModel->add($data);
        if($res) {
            $address = $addressModel->where(array('id'=>$res))->find();
            return_json(0,'添加成功',$address);
        }else{
            return_json(1,'添加失败，请重试');
        }
    }
    public function deleteAddress() {
        $id = get('id');
        $addressModel = M('address');
        $res = $addressModel->where(array('id'=>$id,'uid'=>$this->uid))->delete();
        if($res){
            return_json(0,'删除成功');
        }else{
            return_json(0,'删除失败');
        }
    }

    public function getGoodsList () {
        $grade = get('grade');
        if($grade==3) {
            $where = array(
                'is_grade3' => 1
            );
        }elseif($grade==4) {
            $where = array(
                'is_grade4' => 1
            );
        }elseif($grade==2) {
            $where = array(
                'grade_id' => 2,
                'shop_price' => '39.9'
            );
        }
        $list = $this->goodsModel->where($where)->field(
            'goods_name,goods_pic,goods_id'
        )->select();
       

        if(!$list) {
            return_json(1,'');
        }
        foreach($list as $k=>$v) {
            $list[$k]['goods_pic'] = C('UPYUN_DOMAIN').$v['goods_pic'];
            $list[$k]['num'] = 0;
        } 
        return_json(0,'',$list);
    }


    /* public function test () {
        $where = array(
            'level' => 3,
        );
        $list = $this->areaModel->where($where)->select();
        foreach($list as $v) {
            $city = $this->areaModel->where("area_id={$v['parentid']}")->find();
            $all_name = $city['all_name'].'-'.$v['area_name'];
            $this->areaModel->where("area_id={$v['area_id']}")->setField('all_name',$all_name);
        }
    } */
}